<template>
    <view class="px-[42rpx] pt-[52rpx]">
        <image src="/static/images/img/lfangz.png" class="w-[368rpx] h-[368rpx] ml-[191rpx]"></image>
        <view class="px-[98rpx]">
            <text class="text-[28rpx] text-[#000000] font-[PingFang SC] font-[500]">家庭名字叫什么？</text>
            <view class="h-[80rpx] mt-[10rpx]">
                <up-input placeholder="请输入家庭名称" border="none" v-model="formData.family.name" shape="circle" :customStyle="{
                    backgroundColor: '#FFFFFF',
                    height: '40px',
                    padding: '12rpx',
                    paddingLeft: '42rpx',
                    fontSize: '25rpx'
                }"></up-input>
            </view>
            <view class="mt-[24rpx]">
                <text class="text-[28rpx] text-[#000000] font-[PingFang SC] font-[500]">设置你的家庭邀请码(非必填)</text>
                <view class="h-[80rpx] mt-[10rpx]">
                    <up-input placeholder="请输入家庭邀请码" border="none" v-model="formData.family.code" shape="circle" :customStyle="{
                    backgroundColor: '#FFFFFF',
                    height: '40px',
                    padding: '12rpx',
                    paddingLeft: '42rpx',
                    fontSize: '25rpx'
                }"></up-input>
                </view>
            </view>
            <view class="mt-[24rpx]">
                <text class="text-[28rpx] text-[#000000] font-[500]">请选择家庭下的宠物</text>
                <view class="h-[80rpx] mt-[16rpx] relative" @click="showPetSelector = true">
                    <view class="bg-white rounded-full h-[80rpx] flex items-center px-[42rpx] text-[28rpx]" :class="selectedPetNames.length ? 'text-[#333]' : 'text-[#999]'">
                        <text>{{ selectedPetNames.length ? selectedPetNames.join('、') : '请选择宠物' }}</text>
                        <view class="absolute right-[30rpx]">
                            <image src="@/static/images/img/xia.png" class="w-[36rpx] h-[20rpx]"></image>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <view class="w-[538rpx] h-[108rpx] text-[#000000] fixed bottom-[80rpx]" 
              style="border-radius: 400rpx;left: 50%; transform: translateX(-50%)"
              @click="submitForm">
            <image src="@/static/images/img/createhome.png" class="w-[538rpx] h-[108rpx]"></image>
        </view>
        
        <!-- 宠物选择弹窗 -->
        <up-popup :show="showPetSelector" @close="showPetSelector = false" mode="bottom" round="10">
            <view class="p-[30rpx]">
                <view class="text-center text-[32rpx] font-[500] mb-[30rpx]">选择宠物</view>
                <up-checkbox-group v-model="formData.petIds" iconPlacement="left" placement="column" @change="checkboxChange">
                    <view v-if="petList.length > 0">
                        <up-checkbox
                            v-for="(pet, index) in petList"
                            :key="pet.id"
                            :name="pet.id"
                            :customStyle="{marginRight: '0', width: '100%'}"
                        >
                            <template #label>
                                <view class="flex items-center">
                                    <image :src="pet.avatar" class="w-[80rpx] h-[80rpx] rounded-full mr-[20rpx]" />
                                    <view>
                                        <view class="text-[28rpx] font-[500]">{{ pet.name }}</view>
                                        <view class="text-[24rpx] text-[#999]">{{ pet.type }}</view>
                                    </view>
                                </view>
                            </template>
                        </up-checkbox>
                    </view>
                    <view v-else class="py-[40rpx] text-center text-[28rpx] text-[#999]">
                        暂无宠物，请先添加宠物
                    </view>
                </up-checkbox-group>
                
                <view class="mt-[30rpx] flex gap-[20rpx]">
                    <button class="flex-1 h-[90rpx] bg-[#F5F5F5] text-[#333] rounded-[100rpx] flex items-center justify-center"
                            @click="showPetSelector = false">
                        取消
                    </button>
                    <button class="flex-1 h-[90rpx] bg-[#C0FF00] text-[#000] rounded-[100rpx] flex items-center justify-center font-bold"
                            @click="confirmPetSelection">
                        确定
                    </button>
                </view>
            </view>
        </up-popup>
    </view>
</template>

<script setup>
import {ref, computed} from 'vue'
import {createFamily} from '@/api/home.js'
import {getPetList} from '@/api/pet.js'
import {onShow} from '@dcloudio/uni-app'
import useUserStore from '@/store/modules/user';

const userStore = useUserStore();
const formData = ref({
    petIds: [], // 宠物id数组
    family: {
        code: '', // 家庭邀请码
        updateTime: '', // 更新时间
        remark: '', // 备注
        avatar: '', // 头像
        uid: userStore.userId, // 用户id
        name: '', // 家庭名称
    }
});

const petList = ref([]); // 宠物列表
const showPetSelector = ref(false); // 是否显示宠物选择弹窗

// 获取宠物列表
const fetchPetList = () => {
    const params = {
        uid: userStore.userId
    };
    
    getPetList(params).then(res => {
        if (res.code === 200) {
            petList.value = res.rows || [];
        } else {
            uni.showToast({
                title: res?.msg || '获取宠物列表失败',
                icon: 'none'
            });
        }
    }).catch(err => {
        console.error('获取宠物列表失败:', err);
        uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none'
        });
    });
};

// 计算已选择的宠物名称
const selectedPetNames = computed(() => {
    if (!formData.value.petIds.length || !petList.value.length) return [];
    
    return formData.value.petIds.map(id => {
        const pet = petList.value.find(item => item.id === id);
        return pet ? pet.name : '';
    }).filter(name => name);
});

// 复选框变化事件
const checkboxChange = (e) => {
    console.log('选中的宠物ID:', e);
};

// 确认宠物选择
const confirmPetSelection = () => {
    showPetSelector.value = false;
};

// 提交表单
const submitForm = () => {
    // 表单验证
    if (!formData.value.family.name) {
        uni.showToast({
            title: '请输入家庭名称',
            icon: 'none'
        });
        return;
    }
    
    if (!formData.value.petIds.length) {
        uni.showToast({
            title: '请选择至少一个宠物',
            icon: 'none'
        });
        return;
    }
    
    // 显示加载中
    uni.showLoading({
        title: '创建中...'
    });
    
    // 调用API创建家庭
    createFamily(formData.value).then(res => {
        uni.hideLoading();
        if (res.code === 200) {
            uni.showToast({
                title: '创建成功',
                icon: 'success'
            });
            
            // 创建成功后返回上一页
            setTimeout(() => {
                uni.navigateBack();
            }, 1500);
        } else {
            uni.showToast({
                title: res.msg || '创建失败',
                icon: 'none'
            });
        }
    }).catch(err => {
        uni.hideLoading();
        uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none'
        });
        console.error('创建家庭失败:', err);
    });
};

// 页面加载时获取宠物列表
onShow(() => {
    fetchPetList();
});
</script>

<style scoped lang="scss"></style>